import 'package:flutter/material.dart';
import 'package:flutterapp/src/bean/bean_art.dart';
import 'package:flutterapp/src/net/dio_utils.dart';
import 'package:flutterapp/src/page/home/home_art_list_item_widget.dart';
import 'package:flutterapp/src/utils/log_utils.dart';
import 'package:flutterapp/src/utils/toast_utils.dart';

class HomeItem3Page extends StatefulWidget {
  @override
  _HomeItem3PageState createState() => _HomeItem3PageState();
}

class _HomeItem3PageState extends State<HomeItem3Page> {
  List<ArtModel> _artList = [];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    loadingNetData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("精选文章"),
      ),
      body: NotificationListener<ScrollEndNotification>(
        onNotification: (ScrollEndNotification notification) {
          LogUtils.e("滑动结束了了了");
          //在滑动结束的时候 判断下如果滑动了 2/3数据
          //就自动加载下一页数据
          //获取滑动的距离
          //ScrollMetrics 是保存就滑动相关的信息
          // pixels
          ScrollMetrics scrollMetrics = notification.metrics;
          //获取滑动的距离
          double pixels = scrollMetrics.pixels;
          //获取最大滑动的距离
          double maxPixels = scrollMetrics.maxScrollExtent;
          //获取滑动的方向
          AxisDirection axisDirection = scrollMetrics.axisDirection;

          if (pixels >= maxPixels / 3 * 2 &&
              axisDirection == AxisDirection.down) {
            //加载更多
            LogUtils.e("加载更多");
            loadmore();
          }

          //返回true 阻止再向上发送通知
          return true;
        },
        child: RefreshIndicator(
          onRefresh: onRefresh,
          child: ListView.builder(
            itemCount: _artList.length,
            itemBuilder: (BuildContext context, int index) {
              ArtModel artItem = _artList[index];
              return HomeArtListItemWidget(artItem: artItem);
            },
          ),
        ),
      ),
    );
  }

  // 加载数据
  void loadingNetData() async {
    //添加一下分页请求信息
    Map<String, dynamic> map = new Map();
    //当前页数
    map["pageIndex"] = _pageIndex;
    //每页大小
    map["pageSize"] = _pageSize;
    // // 发起一个http请求
    // ResponseInfo responseInfo =
    //     await DioUtils.instance.getRequest(url: HttpHelper.artList);
    // if (responseInfo.success) {
    //   List list = responseInfo.data;
    //   print("----请求回来的数据");
    //   _artList = [];
    //   list.forEach((v) => _artList.add(ArtModel.fromJson(v)));
    //   setState(() {});
    // } else {
    //   ToastUtils.showToast("请求数据失败");
    // }
    // 使用模拟数据
    ResponseInfo responseInfo =
        await Future.delayed(Duration(milliseconds: 1000), () {
      List list = [];

      for (int i = 0; i < 10; i++) {
        list.add({
          "title": "测试数据$i",
          "userId": 666,
          "body": "这里是测试数据的简介",
        });
      }

      return ResponseInfo(data: list);
    });
    //加载结束标识
    _isLoading = false;
    if (responseInfo.success) {
      List list = responseInfo.data;
      //无数据时 更新索引
      if (list.length == 0 && _pageIndex != 1) {
        _pageIndex--;
      }
      if (_pageIndex == 1) {
        //清空一下数据
        _artList = [];
      }
      list.forEach((element) {
        _artList.add(ArtModel.fromJson(element));
      });
      setState(() {});
    } else {
      ToastUtils.showToast("请求失败");
    }
  }

  // 数显数据

  int _preLoadingTime = 0;
  Future<bool> onRefresh() async {
    _pageIndex = 1;
    // 记录开始时间
    _preLoadingTime = DateTime.now().microsecond;
    // 加载网络请求
    await loadingNetData();
    // 记录结束时间
    int currentTime = DateTime.now().microsecond;
    // 时间差
    int flagTime = currentTime - _preLoadingTime;
    if (flagTime < 1000) {
      await Future.delayed(Duration(milliseconds: 1000 - flagTime));
    }
    ToastUtils.showToast("已刷新");
    return true;
  }

  // 下拉加载更多
  int _pageIndex = 1;
  int _pageSize = 10;
  bool _isLoading = false;

  void loadmore() {
    if (!_isLoading) {
      _isLoading = true;
      _pageIndex++;
      loadingNetData();
    }
  }
}
